<!-- CoachList.vue -->
<template>
  <div>
    <el-page-header content="教练管理">
      <template #extra>
        <div class="page-header-extra">
          <el-input
            v-model="searchQuery"
            placeholder="请输入搜索的内容"
            style="width: 200px; margin-right: 10px;"
            clearable
            @clear="handleSearchClear"
          />
          <el-button type="primary" @click="addDialogVisible = true">增加教练</el-button>
        </div>
      </template>
    </el-page-header>

    <el-table :data="filteredCoaches" style="width: 100%">
      <el-table-column label="序号" width="80" align="center">
        <template #default="scope">
          {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="birthday" label="出生年月" />
      <el-table-column prop="years_of_experience" label="工作年限" />
      <el-table-column prop="address" label="地址" />
      <el-table-column prop="specialization" label="技能专长" />
      <el-table-column label="操作" width="180" fixed="right" align="center">
        <template #default="scope">
          <div class="operation-cell">
            <el-button size="small" type="primary" @click="editCoach(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteCoach(scope.row.coach_id)">
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="editDialogVisible" title="编辑教练信息" width="50%">
      <el-form :model="editForm" label-width="120px" ref="editFormRef" :rules="formRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="editForm.password"
            :type="showOriginalPassword ? 'text' : 'password'"
            show-password
            placeholder="输入新密码（留空保持原密码）"
          />
          <el-button
            size="small"
            @click="showOriginalPassword = !showOriginalPassword"
          >
            {{ showOriginalPassword ? '隐藏' : '显示' }}密码
          </el-button>
          <div v-if="showOriginalPassword" class="original-password-hint">
            原始密码: {{ editForm.password }}
          </div>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" type="email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="editForm.gender" placeholder="请选择">
            <el-option label="男" value="MALE" />
            <el-option label="女" value="FEMALE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>

        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="editForm.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" />
        </el-form-item>

        <el-form-item label="技能专长" prop="specialization">
          <el-select v-model="editForm.specialization" placeholder="请选择">
            <el-option label="个性化教学与学员适应性" value="个性化教学与学员适应性" />
            <el-option label="复杂路况与应急处理教学" value="复杂路况与应急处理教学" />
            <el-option label="考试技巧与规则解析" value="考试技巧与规则解析" />
            <el-option label="沟通与心理建设" value="沟通与心理建设" />
            <el-option label="科技化教学工具应用" value="科技化教学工具应用" />
          </el-select>
        </el-form-item>

        <el-form-item label="工作年限" prop="years_of_experience">
          <el-select v-model="editForm.years_of_experience" placeholder="请选择">
            <el-option
              v-for="year in 50"
              :key="year"
              :label="`${year} 年`"
              :value="year"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新增教练表单 -->
    <el-dialog v-model="addDialogVisible" title="新增教练" width="50%">
      <el-form :model="addForm" label-width="120px" ref="addFormRef" :rules="formRules">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" />
        </el-form-item>

        <el-form-item label="姓名" prop="fullname">
          <el-input v-model="addForm.fullname" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            type="password"
            show-password
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" type="email" />
        </el-form-item>

        <el-form-item label="身份证号" prop="id_number">
          <el-input v-model="addForm.id_number" />
        </el-form-item>

        <el-form-item label="教练证件号码" prop="license_number">
          <el-input v-model="addForm.license_number" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" />
        </el-form-item>

        <el-form-item label="性别" prop="gender">
          <el-select v-model="addForm.gender" placeholder="请选择">
            <el-option label="男" value="MALE" />
            <el-option label="女" value="FEMALE" />
            <el-option label="其他" value="OTHER" />
          </el-select>
        </el-form-item>

        <el-form-item label="出生日期" prop="birthday">
          <el-date-picker
            v-model="addForm.birthday"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" />
        </el-form-item>

        <el-form-item label="入职日期" prop="hire_date">
          <el-date-picker
            v-model="addForm.hire_date"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>

        <el-form-item label="技能专长" prop="specialization">
          <el-select v-model="addForm.specialization" placeholder="请选择">
            <el-option label="个性化教学与学员适应性" value="个性化教学与学员适应性" />
            <el-option label="复杂路况与应急处理教学" value="复杂路况与应急处理教学" />
            <el-option label="考试技巧与规则解析" value="考试技巧与规则解析" />
            <el-option label="沟通与心理建设" value="沟通与心理建设" />
            <el-option label="科技化教学工具应用" value="科技化教学工具应用" />
          </el-select>
        </el-form-item>

        <el-form-item label="工作年限" prop="years_of_experience">
          <el-select v-model="addForm.years_of_experience" placeholder="请选择">
            <el-option
              v-for="year in 50"
              :key="year"
              :label="`${year} 年`"
              :value="year"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <el-pagination
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      layout="total, sizes, prev, pager, next, jumper"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import requestUtil from '@/util/request.js'
import debounce from 'lodash/debounce'

// 数据相关
const coaches = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')

// 表单相关
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = ref({
  username: '',
  password: '',
  email: '',
  phone: '',
  id_number: '',
  fullname: '',
  gender: '',
  birthday: '',
  address: '',
  license_number: '',
  hire_date: '',
  years_of_experience: 0,
  specialization: ''
})

const editDialogVisible = ref(false)
const editFormRef = ref()
const showOriginalPassword = ref(false)
const editForm = ref({
  coach_id: 0,
  username: '',
  password: '',
  email: '',
  phone: '',
  fullname: '',
  gender: '',
  birthday: '',
  address: '',
  license_number: '',
  hire_date: '',
  years_of_experience: 0,
  specialization: ''
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  fullname: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  id_number: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  years_of_experience: [
    {
      required: false,
      trigger: 'blur',
      validator: (rule, value, callback) => {
        if (value === '') {
          callback();
        } else if (!/^\d+$/.test(value)) {
          callback(new Error('工作年限必须为数字'));
        } else {
          callback();
        }
      }
    }
  ]
}

// 计算属性：过滤教练数据
const filteredCoaches = computed(() => {
  if (!searchQuery.value) {
    return coaches.value;
  }

  const query = searchQuery.value.toLowerCase();
  return coaches.value.filter(coach => {
    return (
      (coach.username && coach.username.toLowerCase().includes(query)) ||
      (coach.fullname && coach.fullname.toLowerCase().includes(query)) ||
      (coach.phone && coach.phone.includes(query)) ||
      (coach.address && coach.address.toLowerCase().includes(query)) ||
      (coach.years_of_experience && coach.years_of_experience.toString().includes(query)) ||
      (coach.specialization && coach.specialization.includes(query))
    );
  });
})

// 搜索处理
const handleSearchClear = () => {
  searchQuery.value = '';
  fetchCoaches();
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchCoaches();
}

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchCoaches();
}

// 数据获取
const fetchCoaches = async () => {
  try {
    const response = await requestUtil.get('/coach/msg', {
      page: currentPage.value,
      page_size: pageSize.value
    })
    coaches.value = response.data.data
    total.value = response.data.total;
  } catch (error) {
    console.error('获取教练列表失败:', error)
    ElMessage.error('获取教练列表失败')
  }
}

// 教练操作
const editCoach = async (row) => {
  try {
    const res = await requestUtil.get(`/coach/msg/${row.coach_id}`)
    editForm.value = {
      ...res.data.data,
      hire_date: res.data.data.hire_date || new Date().toISOString().split('T')[0]
    }
    editDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取教练信息失败')
  }
}

const deleteCoach = async (id) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个教练吗？此操作不可恢复！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await requestUtil.del(`/coach/delete/${id}`)
    if (response.data?.status === 200) {
      ElMessage.success('删除成功')
      await fetchCoaches()
    } else {
      ElMessage.error(response.data?.message || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel' || error === 'close') {
      ElMessage.info('已取消删除')
      return
    }
    ElMessage.error(error.response?.data?.message || '删除失败')
  }
}

// 表单提交
const submitAddForm = async () => {
  try {
    const valid = await addFormRef.value.validate();
    if (!valid) {
      ElMessage.error('请填写完整信息');
      return;
    }

    await requestUtil.post('/coach/add', addForm.value)
    addDialogVisible.value = false
    ElMessage.success('新增成功')
    await fetchCoaches()
  } catch (error) {
    ElMessage.error(`新增失败: ${error.response?.data?.message || error.message}`)
  }
}

const submitEditForm = async() => {
  try {
    const valid = await editFormRef.value.validate()
    if (!valid) {
      ElMessage.error('请填写完整信息')
      return
    }

    await requestUtil.put(
      `/coach/update/${editForm.value.coach_id}`,
      editForm.value
    )
    editDialogVisible.value = false
    ElMessage.success('更新成功')
    await fetchCoaches()
  } catch (error) {
    ElMessage.error(`更新失败: ${error.response?.data?.message || error.message}`)
  }
}

// 生命周期
onMounted(() => {
  fetchCoaches()
})
</script>

<style scoped>
.operation-cell .el-button {
  margin-right: 8px;
}

.operation-cell .el-button:last-child {
  margin-right: 0;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.page-header-extra {
  display: flex;
  align-items: center;
}

.original-password-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}
</style>
